package com.sicheng.metadata.juc.forkjoin;

import java.util.concurrent.RecursiveTask;

public class CustomTask extends RecursiveTask<Long> {

    private static final long VALUE = 10000000;
    private final long begin;
    private final long end;
    private long result;

    public CustomTask(long begin, long end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if ((end - begin) <= VALUE) {
            for (long i = begin; i <= end; i++) {
                result = (begin + end) * (end - begin + 1) / 2;
            }
        } else {
            long mid = begin + (end - begin) / 2;
            CustomTask task1 = new CustomTask(begin, mid);
            CustomTask task2 = new CustomTask(mid + 1, end);
            task1.fork();
            task2.fork();
            result = task1.join() + task2.join();
        }
        return result;
    }
}
